#region MIT Licence
/*
 * Copyright (C) 2014 PdfCreative
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom 
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included 
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE 
 * AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace PdfCreative.Pdf.Writer
{
    /// <summary>
    /// The CrossReference class manages the PDF document's cross-reference table (xref). It maintains a list of objects that
    /// have been written to the PDF file, and their location within the file stream. The CrossReference can generate the required
    /// xref output at command.
    /// </summary>
    internal class CrossReference
    {
        // Private fields
        // ==============
        #region Private fields
        private Dictionary<PdfObjectReference, long> _crossReference;
        #endregion



        // Public methods
        // ==============
        #region Public methods
        /// <summary>
        /// Adds a new object reference to the cross-reference
        /// </summary>
        /// <param name="reference">The object reference</param>
        /// <param name="position">The position in the stream of the object</param>
        public void Add(PdfObjectReference reference, long position)
        {
            if (null == reference)
                throw new ArgumentNullException("reference");

            _crossReference[reference] = position;
        }

        /// <summary>
        /// Writes the cross-reference table to the stream for the objects specified in the start and end arguments.
        /// </summary>
        /// <param name="stream">The stream to write to</param>
        /// <param name="start">Index of the first object to write. This value can be 0, indicating that the cross-reference
        /// should output the special 0-entry, or any non-negative integer.</param>
        /// <param name="end">Index of the last object to write. This must be a positive integer, and equal to or larger than the value
        /// of the start argument</param>
        /// <exception cref="ArgumentException">The end value is less than the start value</exception>
        /// <exception cref="ArgumentNullException">The stream reference is null</exception>
        /// <exception cref="ArgumentOutOfRangeException">The value of start is less than 0, or the value
        /// of end is less than 1.</exception>
        /// <exception cref="WriterCrossReferenceException">A PDF object was created but never added to the PDF document stream</exception>
        public void Write(Stream stream, int start, int end)
        {
            if (null == stream) throw new ArgumentNullException("stream");
            if (start < 0) throw new ArgumentOutOfRangeException("start", "The value of 'start' must be 0 or greater");
            if (end <= 0) throw new ArgumentOutOfRangeException("end", "The value of 'end' must be 1 or greater");
            if (end < start) throw new ArgumentException("The 'end' value must not be smaller than the 'start' value", "end");

            // Each line is 20 bytes including a carriage return and newline
            byte[] buffer = new byte[20];
            buffer[18] = (int)'\r';
            buffer[19] = (int)'\n';

            // If the first object index is 0, we write the special 0 entry.
            if (start == 0)
            {
                Encoding.ASCII.GetBytes("0000000000 65535 f", 0, 18, buffer, 0);
                stream.Write(buffer,0,buffer.Length);
                start++;
            }

            // Write each object to the cross-reference.
            // If an object is missing, it has not been added to the PDF document and we throw an exception.
            for(int objectId = start; objectId<=end; objectId++)
            {
                PdfObjectReference objRef = new PdfObjectReference(objectId, 0);
                if (_crossReference.ContainsKey(objRef))
                {
                    long offset = _crossReference[objRef];
                    Encoding.ASCII.GetBytes(
                        String.Format("{0:0000000000} 00000 n", offset), 0, 18, buffer, 0);
                    stream.Write(buffer, 0, buffer.Length);
                }
                else
                    throw new WriterCrossReferenceException(String.Format(
                        "The object {0} has been created, but was never added to the PDF document stream", objRef));
            }
        } // Write()
        #endregion



        // Public constructor
        // ==================
        #region Public constructor
        /// <summary>
        /// Constructs a new CrossReference instance.
        /// </summary>
        public CrossReference()
        {
            _crossReference = new Dictionary<PdfObjectReference, long>();
        }
        #endregion
    }
}
